package com.lw.leetcode.arr;

/**
 * @Author liw
 * @Date 2021/5/12 14:52
 * @Version 1.0
 */
public class Trap {
    public int trap(int[] height) {
        int length = height.length - 1;
        if (length < 2) {
            return 0;
        }

        int st = 0;
        int end = length;

        int sum = 0;
        while (st < end) {
            if (height[st] <= height[end]) {
                int h = height[st];
                while (st <= end && height[st] <= h) {
                    sum = sum + (h - height[st]);
                    st++;
                }
            } else {
                int h = height[end];
                while (end >= st && height[end] <= h) {
                    sum = sum + (h - height[end]);
                    end--;
                }
            }
        }
        return sum;
    }
}
